﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Dtos;
using Work.Domain;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Read.CommandHandlers
{
    /// <summary>
    /// 获取预约列表处理器
    /// </summary>
    public class GetAppointmentsQueryHandler : IRequestHandler<GetAppointmentsQuery, ApiResult<List<AppointmentListDto>>>
    {
        private readonly IBaseRepository<Appintment> _appointmentRepo;
        private readonly IMapper _mapper;

        public GetAppointmentsQueryHandler(IBaseRepository<Appintment> appointmentRepo, IMapper mapper)
        {
            _appointmentRepo = appointmentRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<AppointmentListDto>>> Handle(GetAppointmentsQuery request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<AppointmentListDto>>();

            try
            {
                var query = _appointmentRepo.GetAll()
                    .Include(a => a.Patient)
                    .AsNoTracking();

                // 动态构建查询条件
                if (!string.IsNullOrWhiteSpace(request.CardNumber))
                {
                    query = query.Where(a => a.CardNumber == request.CardNumber);
                }

                if (!string.IsNullOrWhiteSpace(request.PatientName))
                {
                    query = query.Where(a => a.Patient != null && a.Patient.PatientName!.Contains(request.PatientName));
                }

                if (!string.IsNullOrWhiteSpace(request.Department))
                {
                    query = query.Where(a => a.Department == request.Department);
                }

                if (!string.IsNullOrWhiteSpace(request.DoctorName))
                {
                    query = query.Where(a => a.DoctorName == request.DoctorName);
                }

                if (request.StartDate.HasValue)
                {
                    query = query.Where(a => a.VisitDate >= request.StartDate.Value);
                }

                if (request.EndDate.HasValue)
                {
                    query = query.Where(a => a.VisitDate <= request.EndDate.Value);
                }

                if (!string.IsNullOrWhiteSpace(request.RecordStatus))
                {
                    query = query.Where(a => a.RecordStatus == request.RecordStatus);
                }

                // 按就诊日期倒序排列
                var appointments = await query
                    .OrderByDescending(a => a.VisitDate)
                    .ToListAsync(cancellationToken);

                // 映射为DTO
                var dtoList = new List<AppointmentListDto>();
                foreach (var appointment in appointments)
                {
                    var dto = _mapper.Map<AppointmentListDto>(appointment);
                    if (appointment.Patient != null)
                    {
                        dto.PatientName = appointment.Patient.PatientName;
                        dto.Gender = appointment.Patient.Gender;
                        dto.Age = appointment.Patient.Age;
                        dto.Phone = appointment.Patient.Phone;
                    }
                    dtoList.Add(dto);
                }

                result.Code = ApiEnum.成功;
                result.Message = "查询成功";
                result.Data = dtoList;
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"查询失败：{ex.Message}";
                result.Data = new List<AppointmentListDto>();
            }

            return result;
        }
    }
}








